#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: aliyun_upload.py
@contact: zwb15083976291@163.com
@time: 2021/11/30
"""
import base64
import hmac
import json
from datetime import datetime, time
import random

import oss2
from django.conf import settings


class AliUploadToken(object):

    def __init__(self, ali_bucket_dir):
        self.ali_bucket_dir = ali_bucket_dir
        self.bucket = oss2.Bucket(
            oss2.Auth(getattr(settings, "ALI_ACCESS_KEY_ID"), getattr(settings, "ALI_ACCESS_KEY_SECRET")),
            getattr(settings, "ALI_ENDPOINT"), getattr(settings, "ALI_BUCKET_NAME"))

    @property
    def get_image_name(self):
        return self.ali_bucket_dir + str(random.randint(1, 99999)) + "-" + datetime.now().strftime(
            "%Y%m%d%H%M%S") + (".png" if self.ali_bucket_dir == "images/" else ".mp3")

    def get_upload_image_token(self):
        print(self.get_image_name)
        token = self.bucket.sign_url('PUT', self.get_image_name, 60, headers={'Content-Type': 'multipart/form-data'},
                                     slash_safe=True)
        return token
